/**
 * Copyright 2011 Mathieu Magnaudet
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.enac.geoapp.gui.component;

import java.awt.FlowLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;

import org.apache.log4j.Logger;

import edu.enac.geoapp.gui.custom.component.RangeSelectorComponent;
import edu.enac.geoapp.gui.custom.component.RangeSelectorPanel;
import edu.enac.geoapp.gui.listener.RangeListener;
import edu.enac.geoapp.model.Range;
import edu.enac.geoapp.services.DataProvider;

/**
 * 
 * @author mathieu
 * Component to select a range
 * NOT FULLY IMPLEMENTED
 */
@SuppressWarnings("serial")
public class RangeSelectorContainer extends JComponent {
	private List<RangeListener> listeners;
	private static Logger logger = Logger
			.getLogger(RangeSelectorContainer.class);

	private int range; 
	
	public RangeSelectorContainer() {
		listeners = new ArrayList<RangeListener>();
		range = Range.values()[0].getRange();
		
		final RangeSelectorPanel rangeSelector = new RangeSelectorPanel(
				DataProvider.getInstance().getRangeValues());
		final RangeSelectorComponent dropDown = new RangeSelectorComponent(
				rangeSelector, range);
		
		rangeSelector.addPropertyChangeListener("selectedRange",
				new PropertyChangeListener() {

					@Override
					public void propertyChange(PropertyChangeEvent evt) {
						dropDown.hidePopup();
						String newValue = (String) evt.getNewValue();
						try {
							Integer.parseInt(newValue);
							dropDown.changeValue(newValue);
							alertListeners(newValue);
						} catch (NumberFormatException e) {
							logger.error("Range incorrect");
						}

					}
				});
		setLayout(new FlowLayout(FlowLayout.CENTER, 10, 0));
		add(dropDown);
	}

	private void alertListeners(String newValue) {
		if (newValue != null && !newValue.isEmpty()) {
			int newIntValue = 0;
			newIntValue = Integer.parseInt(newValue);
			for (RangeListener r : listeners) {
				r.rangeChanged(newIntValue);
			}
		}
	}

	public void addRangeListener(RangeListener l) {
		listeners.add(l);
	}

	public void removeRangeListener(RangeListener l) {
		listeners.remove(l);
	}
}
